package com.example.springbott.service;

import com.example.springbott.bean.InfoData;
import com.example.springbott.bean.MarketAdmin;
import com.example.springbott.bean.MarketRoleExample;
import com.example.springbott.bean.common.PasswordBO;
import com.example.springbott.mapper.MarketAdminMapper;
import com.example.springbott.mapper.MarketPermissionMapper;
import com.example.springbott.mapper.MarketRoleMapper;
import com.example.springbott.util.Count;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author 1784549954@qq.com
 * @since 2022/11/21 20:46
 */
@Service
public class AuthServiceImpl implements AuthService{


    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    @Autowired
    MarketAdminMapper marketAdminMapper;


    @Override
    public InfoData AuthInfo() {
        InfoData infoData = new InfoData();
        MarketAdmin principal = (MarketAdmin) SecurityUtils.getSubject().getPrincipal();
        Integer[] roleIds = principal.getRoleIds();
        List<String> roles = marketRoleMapper.selectName(roleIds);
        List<String> permissions= marketPermissionMapper.selectPermissions(roleIds);
        List<String> list;
        if (permissions.contains("*")){
            list = marketPermissionMapper.selectApiAll();
        }else{
           list = marketPermissionMapper.selectApi(permissions);
        }

        infoData.setPerms(list);
        infoData.setRoles(roles);
        infoData.setAvatar(principal.getAvatar());
        infoData.setName(principal.getUsername());
        return infoData;

    }

    @Override
    public int AdminPassword(PasswordBO passwordBO, Integer id) {
        int code = Count.SUCCESS_CODE;
        String password = marketAdminMapper.selectPasswordById(id);
        if (password.equals(passwordBO.getOldPassword())){
            marketAdminMapper.updatePassword(passwordBO.getNewPassword(),id);
            return code;
        }else {
            return Count.ERROR_CODE;
        }

    }
}
